package mt.client.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import mt.Order;
import mt.client.ConnectionException;
import mt.client.ListUpdater;
import mt.comm.*;
/**
 * This is the ActionListener called clicking the purchase bottom.
 * A correct input will result in an order sent to the Server.
 * @author tom93d
 *
 */
public class PurchaseListener implements ActionListener {

	private final ClientComm clientComm;
	private String nickName, stock, numberOfUnits, pricePerUnit;
	/**
	 * This constructor creates a PurchaseListener receiving the ClientComm and the nickName of the current client.
	 * @param clientComm
	 * @param nickName
	 */
	public PurchaseListener(ClientComm clientComm, String nickName) {
		this.clientComm = clientComm;
		this.nickName = nickName;
	}
	@Override
	public void actionPerformed(ActionEvent buttonPurchaseEvents) {
		int number;
		double price;
		try {
			if(!clientComm.isConnected()) throw new ConnectionException("No server connection");
			
			stock = JOptionPane.showInputDialog("Insert the name of the Unit?");
			if(stock.equals(null) || stock.equals("")) throw new NullPointerException();
			
			numberOfUnits = JOptionPane.showInputDialog("How many Units you want to Purchase?");
			if(numberOfUnits.equals(null)) throw new NullPointerException();
			
			pricePerUnit = JOptionPane.showInputDialog("What's the pricePerUnit?");
			if(pricePerUnit.equals(null)) throw new NullPointerException();
			
			try {
				number = Integer.parseInt(numberOfUnits);
				price = Double.parseDouble(pricePerUnit);
				Order order = Order.createBuyOrder(nickName, stock, number, price);
				clientComm.sendOrder(order);
			} catch(NumberFormatException e) {
				System.err.println(e.getMessage());
				JOptionPane.showMessageDialog(null,"Invalid argument", "ERROR" ,JOptionPane.ERROR_MESSAGE);
			}

		} catch(NullPointerException e) {
			System.out.println("Null input");
			JOptionPane.showMessageDialog(null,"Order deleted.", "Attention" ,JOptionPane.INFORMATION_MESSAGE);
		} catch(ConnectionException e) {
			System.out.println(e.getMessage());
			JOptionPane.showMessageDialog(null,"You are not connected to the server", "ERROR" ,JOptionPane.ERROR_MESSAGE);
		}
	}

}
